package com.itany.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/11/14 10:08
 * Version:1.0-SNAPSHOT
 * Description: 事务操作
 */
public class Test09 {

    public static void main(String[] args) throws SQLException {
        User user = new User("马超","123456","13112345678","王者荣耀");
        insertUser(user);
    }

    public static void insertUser(User user) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            // 开启事务
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getPhone());
            ps.setString(4,user.getAddress());
            ps.executeUpdate();
            // 此时手动给个异常
            // 如果没有事务,则数据成功添加
            // 如果存在事务,会跳转到catch中进行回滚,数据添加失败
            int i = 1/0;
            // 提交事务
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            conn.rollback();
        } finally {
            JDBCUtil.close(conn,ps,null);
        }
    }

}
